package cn.smart.service.impl;

import cn.smart.mapper.GardenMapper;
import cn.smart.pojo.Garden;
import cn.smart.pojo.GardenExample;
import cn.smart.service.GardenService;
import cn.smart.util.*;
import com.sun.tools.javac.comp.Infer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Xiezh
 * @Description:
 * @create 2017/7/31
 */
@Service
public class GardenServiceImpl implements GardenService {
    @Autowired
    private GardenMapper gardenMapper;

    @Value("${garden.flowerNumber}")
    private int gardenFlowerNumber;
    @Value("${garden.flowerOp}")
    private int gradenFloerOp;
    @Value("${garden.result.flag}")
    private String flag;//硬件返回的第一个标志
    @Value("${garden.result.flag2}")
    private String flag2;//硬件返回的第二个标志
    @Value("{$garden.gardenName}")//花园的默认名
    private String defaultGardenName;

    @Value("${FTP_ADDRESS}")
    private String ftpAddress;//ftp地址
    @Value("${FTP_PORT}")
    private int ftpPort;//ftp端口号
    @Value("${FTP_USERNAME}")
    private String ftpUserName;//ftp账号
    @Value("${FTP_PASSWORD}")
    private String ftpPassword;//ftp密码
    @Value("${FTP_BASE_PATH}")
    private String ftpBasePath;//花园照片在ftp服务器上保存的位置

    /**
     * 失败的操作
     *
     * @param e
     * @return
     */
    private SmartResult getFailResult(Exception e) {
        return new SmartResult(500, Info.FAIL, ExceptionUtil.getStackTrace(e));
    }

    /**
     * 新增花园
     * 非硬件端的操作
     * 必须包含花园的所属用户主键和花园的mac地址
     *
     * @param garden
     * @return
     */
    @Override
    public SmartResult insertGarden(Garden garden) {
        //检测参数是否缺失
        if (garden.getGmac() == null || garden.getGuid() == null) {
            //参数缺失
            return new SmartResult(200, Info.NOT_EXIST, "缺少所属用户主键或者花园mac地址");
        }
        //如果客户端没有传递最大花卉数量的值，将使用默认的最大数
        if (garden.getGmax() == null) garden.setGmax(gardenFlowerNumber);
        //如果用户没有给花园取名字，将使用默认的花园名
        if (garden.getGname() == null || StringUtils.isEmpty(garden.getGname())) {
            garden.setGname(defaultGardenName);
        }
        garden.setGop(gradenFloerOp);
        garden.setGtime(new Date());
        try {
            gardenMapper.insert(garden);
            return new SmartResult(200, Info.SUCCESS, null);
        } catch (Exception e) {
            e.printStackTrace();
            return getFailResult(e);
        }
    }

    /**
     * 删除花园
     *
     * @param gid
     * @return
     */
    @Override
    public SmartResult deleteGarden(int gid) {
        //查询花园，确认花园是否存在
        GardenExample example = new GardenExample();
        GardenExample.Criteria criteria = example.createCriteria();
        criteria.andGidEqualTo(gid);
        List<Garden> gardenList = gardenMapper.selectByExample(example);
        if (gardenList.size() == 0) {
            //没有查询到要删除的花园
            return new SmartResult(200, Info.NOT_EXIST, null);
        }
        //花园存在进行删除
        try {
            gardenMapper.deleteByPrimaryKey(gid);
            return new SmartResult(200, Info.SUCCESS, null);
        } catch (Exception e) {
            e.printStackTrace();
            return getFailResult(e);
        }
    }

    /**
     * 更新花园
     * 不可以修改花园的mac地址和主键
     * 不可以操作花园的op(操作标识位)
     * 不可以操作花园的guid（所属用户主键） 更改花园的所有权单独设立服务
     *
     * @param garden
     * @return
     */
    @Override
    public SmartResult updateGarden(Garden garden) {
        //根据花园的主键查询原有的花园
        GardenExample example = new GardenExample();
        GardenExample.Criteria criteria = example.createCriteria();
        criteria.andGidEqualTo(garden.getGid());
        List<Garden> gardenList = gardenMapper.selectByExample(example);
        if (gardenList.get(0) == null) {
            //没有查询到花园
            return new SmartResult(200, Info.NOT_EXIST, null);
        }
        Garden updateGarden = gardenList.get(0);
        //更新花园名
        if (garden.getGname() != null && StringUtils.isEmpty(garden.getGname())) {
            updateGarden.setGname(garden.getGname());
        }
        //更新花园的最大花路数
        if (garden.getGmax() != null && garden.getGmax() != 0) {
            updateGarden.setGmax(garden.getGmax());
        }
        //设置op为1
        updateGarden.setGop(1);
        //更新花园
        try {
            gardenMapper.updateByPrimaryKey(updateGarden);
            return new SmartResult(200, Info.SUCCESS, null);
        } catch (Exception e) {
            e.printStackTrace();
           return getFailResult(e);
        }
    }

    /**
     * 根据用户的主键，查询用户名下所有的花园
     *
     * @param uid
     * @return
     */
    @Override
    public SmartResult getUsersAllGarden(int uid) {
        GardenExample example = new GardenExample();
        GardenExample.Criteria criteria = example.createCriteria();
        criteria.andGuidEqualTo(uid);
        List<Garden> gardenList = gardenMapper.selectByExample(example);
        return new SmartResult(200, Info.SUCCESS, gardenList);
    }

    /**
     * 根据花园的id查询花园
     *
     * @param gid
     * @return
     */
    @Override
    public SmartResult getGardenByGid(int gid) {
        Garden garden = gardenMapper.selectByPrimaryKey(gid);
        return new SmartResult(200, Info.SUCCESS, garden);
    }

    /**
     * 根据花园的mac地址查询花园
     *
     * @param gmac
     * @return
     */
    @Override
    public SmartResult getGardenByGmac(String gmac) {
        GardenExample example = new GardenExample();
        GardenExample.Criteria criteria = example.createCriteria();
        criteria.andGmacEqualTo(gmac);
        List<Garden> gardenList = gardenMapper.selectByExample(example);
        return new SmartResult(200, Info.SUCCESS, gardenList.get(0));
    }

    /**
     * 上传花园的图片
     *
     * @param file
     * @return
     */
    @Override
    public SmartResult uploadGardenPic(MultipartFile file, int gid) {
        String filename = file.getOriginalFilename();
        String[] split = filename.split(".");
        String prex = split[split.length - 1];
        String picname = UUID.randomUUID() + "." + prex;
        try {
            FtpUtil.uploadFile(ftpAddress, ftpPort, ftpUserName, ftpPassword, ftpBasePath, "/garden", picname, file.getInputStream());
            //将文件保存的位置存放到数据库
            //找到花园
            Garden garden = gardenMapper.selectByPrimaryKey(gid);
            //修改花园的图片地址
            garden.setGpic(ftpAddress + "/" + picname);
            return new SmartResult(200, Info.SUCCESS, garden.getGpic());
        } catch (Exception e) {
            e.printStackTrace();
            return getFailResult(e);
        }
    }

}
